import { NavBar, InfiniteScroll, Toast, Popup } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { useEffect, useState, useRef } from 'react'
import classNames from 'classnames'
import styles from './index.module.scss'
import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import NoComment from './components/NoComment'
import { getArticleInfo, getCommentList, followUser, addComment } from '@/store/actions/article'
import dayjs from 'dayjs'
import { useInitState } from '@/utils/hooks'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
// import { RootState } from '@/types/store'
import CommentInput from './components/CommentInput'
import CommentReply from './components/CommentReply'
import { Comment } from '@/types/data'


const Article = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const Params = useParams<{ id: string }>()
  // 获取动态路由参数
  const articleId = Params.id
  // useEffect(() => {
  //   dispatch(getArticleInfo(articleId))
  // }, [dispatch, articleId])

  // 获取文章详情信息
  // const { info } = useSelector((state: RootState) => state.article)
  const { info } = useInitState(() => getArticleInfo(articleId), 'article')
  //  获取评论
  const { comment } = useInitState(() => getCommentList(articleId), 'article')

  // 关注/取消关注
  const onFollowUser = async () => {
    await dispatch(followUser(info.aut_id, info.is_followed))
    Toast.show('操作成功')
  }

  // 高亮代码----------------------------
  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [info])

  // 是否显示顶部信息
  const [isShowHeader, setIsShowHeader] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const wrapRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const wrapDOM = wrapRef.current!
    const authDOM = authorRef.current!
    const onScroll = () => {
      // console.log('滚动事件')
      const { top } = authDOM.getBoundingClientRect()
      // console.log(top)
      if (top <= 0) {
        setIsShowHeader(true)
      } else {
        setIsShowHeader(false)
      }
    }
    wrapDOM.addEventListener('scroll', onScroll)
    return () => {
      wrapDOM.removeEventListener('scroll', onScroll)
    }
  })

  // 评论无限滚动
  const hasMore = comment.end_id !== comment.last_id
  const loadMore = async () => {
    await dispatch(getCommentList(articleId, comment.last_id))
  }

  // 点击评论-快捷跳转  评论与顶部的跳转
  // 1. 给wrap注册滚动事件
  // 2. 获取到author距离顶部的具体，如果小于45，显示
  const commentRef = useRef<HTMLDivElement>(null)
  const [isTop, setIsTop] = useState(true)
  const onComment = () => {
    const commentDOM = commentRef.current!
    const wrapDOM = wrapRef.current!
    if (isTop) {
      wrapDOM.scrollTo(0, commentDOM.offsetTop - 50)
    } else {
      wrapDOM.scrollTo(0, 0)
    }
    setIsTop(!isTop)
  }

  // 评论表单显示状态
  const [commentShow, setCommentShow] = useState(false)
  const hideComment = () => {
    setCommentShow(false)
  }
  const showComment = () => {
    setCommentShow(true)
  }

  // 发表评论
  const onAddComment = async (value: string) => {
    console.log('添加评论', value)
    await dispatch(addComment(articleId, value))
    await dispatch(getArticleInfo(articleId))
    Toast.show({
      icon: 'success',
      content: '发表成功',
    })
  }

  // 回复评论
  const [replyShow, setReplyShow] = useState({
    visible: false,
    origin: {} as Comment,
  })

  const hideReply = () => {
    setReplyShow({
      visible: false,
      origin: {} as Comment,
    })
  }
  const onReply = (comment: Comment) => {
    setReplyShow({
      visible: true,
      origin: comment,
    })
  }
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowHeader && (
            <div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span onClick={onFollowUser}
                className={classNames('follow', info.is_followed ? 'followed' : '')}
              >
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        <div className="wrapper" ref={wrapRef}>
          <div className="article-wrapper">
            <div className="header">
              <h1 className="title">{info.title}</h1>

              <div className="info">
                <span>{dayjs(info.pubdate).format('YYYY-MM-DD')}</span>
                <span>{info.read_count} 阅读</span>
                <span>{info.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
                <img src={info.aut_photo} alt="" />
                <span className="name">{info.aut_name}</span>
                <span
                  onClick={onFollowUser}
                  className={classNames('follow', info.is_followed ? 'followed' : '')}
                >
                  {info.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            <div className="content">
              <div className="content-html dg-html"
                dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(info.content || '') }} />
              <div className="date">发布文章时间：{dayjs(info.pubdate).format('YYYY-MM-DD')}</div>
            </div>
          </div>

          <div className="comment">
            <div className="comment-header" ref={commentRef}>
              <span>全部评论（{info.comm_count}）</span>
              <span>{info.like_count} 点赞</span>
            </div>

            <div className="comment-list">
              {
                info.comm_count === 0 ? (
                  <NoComment></NoComment>
                ) :
                  comment.results?.map((item) => (
                    <CommentItem
                      key={item.com_id}
                      type="normal"
                      comment={item}
                      onReply={onReply}
                    ></CommentItem>
                  ))
              }
              <InfiniteScroll
                hasMore={hasMore}
                loadMore={loadMore}
              />
            </div>
          </div>
        </div>

        {/* 底部评论栏 */}
        <CommentFooter onComment={onComment} showComment={showComment} />
      </div>
      {/* 发表评论 */}
      <Popup visible={commentShow} position="right" destroyOnClose>
        <CommentInput
          hideComment={hideComment}
          onAddComment={onAddComment}
        ></CommentInput>
      </Popup>
      {/* 回复评论 */}
      <Popup visible={replyShow.visible} position="right" destroyOnClose>
        <CommentReply hideReply={hideReply} origin={replyShow.origin}></CommentReply>
      </Popup>
    </div>
  )
}

export default Article
